package com.mcc.web.controller.system;

import java.util.Iterator;
import java.util.List;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.mcc.common.core.page.TableDataInfo;
import com.mcc.common.exception.CustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mcc.common.annotation.Log;
import com.mcc.common.constant.UserConstants;
import com.mcc.common.core.controller.BaseController;
import com.mcc.common.core.domain.AjaxResult;
import com.mcc.common.core.domain.entity.SysDept;
import com.mcc.common.enums.BusinessType;
import com.mcc.common.utils.SecurityUtils;
import com.mcc.common.utils.StringUtils;
import com.mcc.system.service.ISysDeptService;

/**
 * 部门信息
 *
 * @author gxy
 */
@Api(tags = "部门")
@ApiSort(8)
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {

    @Autowired
    private ISysDeptService deptService;

    @ApiOperation("获取部门列表")
    @ApiOperationSupport(order = 1)
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult<TableDataInfo<SysDept>> list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return getDataTable(depts);
    }

    @ApiOperation("查询部门列表（排除节点）")
    @ApiOperationSupport(order = 2)
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    @ApiOperation("根据部门编号获取详细信息")
    @ApiOperationSupport(order = 3)
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping("/get/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    @ApiOperation("获取部门下拉树列表")
    @ApiOperationSupport(order = 4)
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    @ApiOperation("新增部门")
    @ApiOperationSupport(order = 6)
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            throw new CustomException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    @ApiOperation("修改部门")
    @ApiOperationSupport(order = 7)
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            throw new CustomException("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            throw new CustomException("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.countNormalChildrenDeptById(dept.getDeptId()) > 0) {
            throw new CustomException("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    @ApiOperation("删除部门")
    @ApiOperationSupport(order = 8)
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            throw new CustomException("存在下级部门,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
